package cn.smbms.controller;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import static java.lang.System.*;

/**
 * @Author: laoyu
 * @Date: 2019/9/4 9:18
 * @Description:
 */
@Controller
@RequestMapping("/file")
public class FileController {
    private Logger logger = Logger.getLogger(FileController.class);

    /**
     * 跳转到文件上传页面
     *
     * @return 文件上传页面
     */
    @RequestMapping("/tofile.html")
    public String toAddFile() {
        return "fileUpload";
    }

    /**
     * 单上传文件
     *
     * @return 上传成功后返回success
     */
    @RequestMapping(value = "/one/upload.html", method = RequestMethod.POST)
    @ResponseBody
    public String addFileSave(@RequestParam("attach") MultipartFile attach, HttpServletRequest request) throws IOException {
        //判断文件是否为空
        if (!attach.isEmpty()) {
            //输出文件名
            logger.debug("============>文件名：" + attach.getOriginalFilename());
            logger.debug("============>文件大小：" + attach.getSize() / 1024 + "K");
            logger.debug("============>文件类型：" + FilenameUtils.getExtension(attach.getOriginalFilename()));
            //上传的目标路径（完整目录+文件名）要包含目标的文件名
            String uploadDir = request.getRealPath("/uploads") + "/" + System.currentTimeMillis() + attach.getOriginalFilename();
            //将附件拷贝到项目编译后的指定目录
            FileUtils.copyInputStreamToFile(attach.getInputStream(), new File(uploadDir));
        }
        return "success";
    }

    /**
     * 多文件上传
     *
     * @return 上传成功后返回success
     */
    @RequestMapping(value = "/more/upload.html", method = RequestMethod.POST)
    @ResponseBody
    public String addMoreFileSave(@RequestParam MultipartFile[] myFiles, HttpServletRequest request)
            throws IOException {
        //判断文件是否为空
        if (myFiles.length != 0) {
            for (MultipartFile myFile : myFiles) {
                //获取myFile的属性
                logger.debug("====>>>文件的属性：" + myFile.getContentType());
                //上传的目标路径（完整目录+文件名）要包含目标的文件名
                String uploadDir = request.getRealPath("/uploads") + "/" + System.currentTimeMillis() + myFile.getOriginalFilename();
                logger.debug("====>>>文件上传的目录：" + uploadDir);
                //创建file对象，指向目标路径
                File destFile = new File(uploadDir);
                //上传：使用FileUtils类中封装好的copyInputStreamToFile()方法实现文件上传
                FileUtils.copyInputStreamToFile(myFile.getInputStream(), destFile);
            }
        }
        return "success";
    }

    @RequestMapping(value = "/download"/*, method = RequestMethod.POST*/)
    public ResponseEntity<byte[]> download(@RequestParam("fileName") String fileName,
                                           HttpServletRequest request) throws Exception {
        //获取服务器上保存文件的路径
        String downloadPath = request.getServletContext().getRealPath("/WEB-INF/resource/images/");
        //拼接包含全路径的文件名
        File file = new File(downloadPath + File.separator + fileName);
        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        //下载完成后显示的文件名
        String downloadFileName = new String(
                fileName.getBytes("UTF-8"), "ISO-8859-1");
        //通知浏览器以附件方式打开文件
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //定义以二进制流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //返回ResponseEntity对象，包含请求头和状态码
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

}
